import type { Dispatch } from "@reduxjs/toolkit"

import { queryCurrencySymbolApi } from "@/api/common"
import { defaultCurrency } from "@/constants/common"
import { RateType } from "@/interface/store/config"
import { localStg } from "@/utils/storage"

import { getCurrencyInfo, init } from "./config.store"
import {
	getBetTypes,
	getRateLimit,
	handleUpdateAllDictList,
	handleUpdateCurrentAccountPeriod,
	handleUpdateMerchantList
} from "./helpers"

export const initAsync = () => async (dispatch: Dispatch) => {
	const currentAccountPeriod = await handleUpdateCurrentAccountPeriod()
	const allDictListsRet = await handleUpdateAllDictList()
	const merchantList = await handleUpdateMerchantList()
	const betTypes = await getBetTypes()
	const platform = (await getRateLimit({ platformFlag: 1, userType: 0, zhanchengFlag: 0 })) as Omit<
		RateType,
		"texasInsuranceRebate" | "valueAddedServiceRebate"
	> | null
	const notPlatform = (await getRateLimit({ platformFlag: 0, userType: 0, zhanchengFlag: 0 })) as Omit<
		RateType,
		"texasInsuranceRebate" | "valueAddedServiceRebate"
	> | null
	const rebate = (await getRateLimit({ platformFlag: 0, userType: 1, zhanchengFlag: 0 })) as Omit<
		RateType,
		"texasInsuranceRebate" | "valueAddedServiceRebate" | "texasRebate"
	> | null
	const texas = (await getRateLimit({ platformFlag: 0, userType: 1, zhanchengFlag: 0 })) as Pick<
		RateType,
		"texasRebate" | "texasInsuranceRebate" | "valueAddedServiceRebate"
	> | null
	const zhanCheng = (await getRateLimit({ platformFlag: 0, userType: 1, zhanchengFlag: 1 })) as Omit<
		RateType,
		"texasInsuranceRebate" | "valueAddedServiceRebate" | "texasRebate"
	> | null
	dispatch(
		init({
			currentAccountPeriod,
			allDictLists: allDictListsRet.allDictLists,
			allDictReady: allDictListsRet.ready,
			merchantList,
			betTypes,
			rebateRate: {
				member: { platform, notPlatform },
				agent: { texas, rebate, zhanCheng }
			}
		})
	)
}

export const getCurrencyInfoAsync = () => async (dispatch: Dispatch) => {
	const [, data] = await queryCurrencySymbolApi()
	const currency = (data ?? defaultCurrency) as Common.CurrencyInfo
	localStg.set("__currency__", currency)

	dispatch(
		getCurrencyInfo({
			currency
		})
	)
}

export const updateCurrentAccountPeriodAsync = () => async (dispatch: Dispatch) => {
	const currentAccountPeriod = await handleUpdateCurrentAccountPeriod()

	dispatch(
		getCurrencyInfo({
			currentAccountPeriod
		})
	)
}
export const handleUpdateMerchantListAsync = () => async (dispatch: Dispatch) => {
	const merchantList = await handleUpdateMerchantList()

	dispatch(
		getCurrencyInfo({
			merchantList
		})
	)
}
